<?php
/**
 * Created by PhpStorm.
 * User: SleepingDog
 * Date: 2018/1/17
 * Time: 10:31
 */
class ZduScreenAction extends BaseAction
{
    public function _initialize()
    {

    }

    //pad端
    public function padIndex()
    {

            $windowId = $this->_request('window_id');

            $type = $this->_request('type');
            $today = strtotime(date("Y-m-d"));
            $mOrder = M("restaurantstyy_order_goods");
            $restaurantId = $this->_request("restaurant_id");

            $p = $this->_request('p') ? $this->_request('p') : 1;
            $num = 2;
            $view = $this->_request('view');
            //搜索条件
            $good_tj = $this->_request("good_tj");
            //type = 1 新菜单; 2 未取菜  默认为新菜单
            $type = $type ? $type : 3;


            if ($type != 3) {
                $where_type = '';
                $window = '';
                // if ($windowId) {
                //     $window = "AND window_id = {$windowId}";
                // }
                //window_id  写死
                $window = " AND (window_id = 49 OR window_id = 56) ";

                $where = '';
                // if ($good_tj) {
                //     $where = "AND (goods_name like '%{$good_tj}%' or order_num = '{$good_tj}')";
                // }
                if ($type == 1) {
                    $type = 0;
                    $where_type = "AND goods_status = {$type}";
                }
                if ($type == 2) {
                    $type = 1;
                    $where_type = "AND goods_status = {$type}";
                }

                // //当天时间
                // $t = time();
                // $start_time = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));  //当天开始时间
                // $end_time = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t)); //当天结束时间

                if ($restaurantId != '') {

                    $goods = $mOrder->field('og_id,goods_id,goods_num,goods_name,order_num,goods_status,window_id,category_id,create_time')
                        ->where("restaurant_id = {$restaurantId} AND create_time>{$today} AND order_num>9000 AND pay_status =1 {$where} {$where_type} {$window} ")->order('create_time DESC')->group('order_num')->select();
                        // echo $mOrder->getLastSql();
                        // var_dump($goods);
                        // die('111');
                    vendor('Py.PinYin');
                    $py = new PinYin();
                    foreach ($goods as $k => $v) {
                        $goods[$k]['alert'] = 0;

                        if ((time() - $v['create_time']) > 1800 && $v['goods_status'] == 0) {
                            $goods[$k]['alert'] = 1;
                        }

                        $goods[$k]['first'] = substr($py->getFirstPY($v['goods_name']), 0, 1);
                        if ($v['window_id'] == 52) {
                            unset($goods[$k]);
                        }
                        if ($v['category_id'] == 125) {
                            unset($goods[$k]);
                        }
                    }
                    $goods = $this->sigcol_arrsort($goods, 'first', SORT_ASC);
                    $goodsTmp = array();
                    foreach ($goods as $key => $v) {
                        $goodsTmp[$v['order_num']][] = '';
                    }
                    $goodsList = $this->page_array($count = 6, $p, $goodsTmp, $order = 0);

                    $this->assign('goods', $goods);
                    $this->assign('goodsList', $goodsList);
                    $this->assign('good_tj', $good_tj);
                }
            }

            if ($type == 3) {

                //搜索条件
                $condition = array();
                $time = date('Y-m-d',time());
                $condition['a.pay_status'] = 1;
                $condition['a.window_id'] = $windowId;
                $condition['a.restaurant_id'] = $restaurantId;
                $condition['a.create_time'] = array('egt', strtotime($time));

                if ($good_tj) {
                    $condition['a.order_num'] = $good_tj;
                }
                //$card = M('CampuscardCard');
                $res = $mOrder
                    ->alias('a')
                    ->join('gc_user as b on a.user_id = b.user_id')
                    ->where($condition)
                    ->field('a.og_id,a.goods_id,a.goods_num,a.goods_name,a.order_num,a.goods_status,a.user_id,a.create_time')
                    ->order('create_time ASC')
                    ->select();

                $goodsTmp = array();
                foreach ($res as $a => $arr) {
                    $res[$a]['alert'] = 0;
                    //$res[$a]['number'] = $card->where(array('user_id'=>$arr['user_id']))->getField('number2');
                    if ((time() - $arr['create_time']) > 1800 && $arr['goods_status'] == 0) {
                        $res[$a]['alert'] = 1;
                    }
                }
                foreach ($res as $key => $v) {
                    $goodsTmp[$v['order_num']][] = $v;
                }
                $goodsList = $this->page_array($count = 6, $p, $goodsTmp, $order = 0);
            }

            // var_dump($goodsList);
        if ($this->isAjax()) {
            $this->ajaxReturn(array('status' => 'S', 'message' => '请求成功', 'data' => $goodsList, 'type' => $type));
        }
        $this->assign('type', $type);
        $this->assign('restaurant_id', $restaurantId);
        $this->assign('window_id', $windowId);
        $this->display('pullindex');
    }

    function page_array($count,$page,$array,$order){
        global $countPage; #定全局变量
        $page=(empty($page))?'1':$page; #判断当前页面是否为空 如果为空就表示为第一页面
        $start=($page-1)*$count; #计算每次分页的开始位置
        if($order==1){
            $array=array_reverse($array);
        }
        $totals=count($array);
        $countPage=ceil($totals/$count); #计算总页面数
        $pageData=array();
        $pageData=array_slice($array,$start,$count,true);
        return $pageData; #返回查询数据
    }
    private function sigcol_arrsort($data,$col,$type=SORT_DESC){
        if(is_array($data)){
            $i=0;
            foreach($data as $k=>$v){
                if(key_exists($col,$v)){
                    $arr[$i] = $v[$col];
                    $i++;
                }else{
                    continue;
                }
            }
        }else{
            return false;
        }
        array_multisort($arr,$type,$data);
        return $data;
    }

    //大屏幕
    public function screenIndex(){
        $today =  strtotime(date("Y-m-d"));
        $M_restaurant = M("restaurantstyy_info");
        $restaurant_id = $this->_get("restaurant_id");
        $restaurant_data = $M_restaurant->where("restaurant_id={$restaurant_id}")->find();

        $page= 8;
        $M_log=M('restaurantstyy_order_goods_log');
        $log_data = $M_log->where("goods_status = 1 AND creation_time >= {$today} AND order_num !=0 AND restaurant_id={$restaurant_id}")->order('creation_time ASC')->select();
        $datas = json_encode(array_chunk($log_data,$page));

        $this->assign('restaurant_name',$restaurant_data['restaurant_name']);
        $this->assign('log_data',$log_data);
        $this->assign('datas',$datas);

        $this->assign('restaurant_id', $restaurant_id);

        $this->display();

    }

    public function oneScreen(){
        $today =  strtotime(date("Y-m-d"));
        $M_restaurant = M("restaurantstyy_info");
        $restaurant_id = $this->_get("restaurant_id");
        $restaurant_data = $M_restaurant->where("restaurant_id={$restaurant_id}")->find();
        $p = $this->_request('p') ? $this->_request('p') :1;
        $num = 3;
        $M_log=M('restaurantstyy_order_goods_log');
        $log_data = $M_log->where("goods_status = 1 AND creation_time >= {$today} AND order_num !=0 AND restaurant_id={$restaurant_id}")->order('creation_time ASC')->select();
        $count = count($log_data);
        if($p>ceil($count/$num)){
            $log_data = $M_log->where("goods_status = 1 AND creation_time >= {$today} AND order_num !=0 AND restaurant_id={$restaurant_id}")->order('creation_time ASC')->limit(0,3)->select();
            $this->assign('p',$p);
            $this->assign('datas',$log_data);
            $this->assign('restaurant_id', $restaurant_id);
            $this->assign('count',count($log_data));
            $this->display();return;
        }
        $page = new Page($count, $num);
        /*        $page->totalPages   =   ceil($page->totalRows/$page->listRows);     //总页数
                if($p>$page->totalPages){

                }*/
        $limit = $page->firstRow . ',' . $page->listRows;
        $log_data = $M_log->where("goods_status = 1 AND creation_time >= {$today} AND order_num !=0 AND restaurant_id={$restaurant_id}")->order('creation_time ASC')->limit($limit)->select();
        $this->assign('restaurant_name',$restaurant_data['restaurant_name']);
        //cprint($log_data);die;
        $this->assign('restaurant_id', $restaurant_id);
        $this->assign('p',$p+2);
        $this->assign('datas',$log_data);
        $this->assign('count',count($log_data));
        $this->display();
    }

    public function twoScreen(){
        $today =  strtotime(date("Y-m-d"));
        $M_restaurant = M("restaurantstyy_info");
        $restaurant_id = $this->_get("restaurant_id");
        $restaurant_data = $M_restaurant->where("restaurant_id={$restaurant_id}")->find();
        $p = $this->_request('p') ? $this->_request('p') :2;
        $num = 3;
        $M_log=M('restaurantstyy_order_goods_log');
        $log_data = $M_log->where("goods_status = 1 AND creation_time >= {$today} AND order_num !=0 AND restaurant_id={$restaurant_id}")->order('creation_time ASC')->select();
        $count = count($log_data);
        if($p>ceil($count/$num)){
            $log_data = $M_log->where("goods_status = 1 AND creation_time >= {$today} AND order_num !=0 AND restaurant_id={$restaurant_id}")->order('creation_time ASC')->limit(3,3)->select();
            $this->assign('datas',$log_data);
            $this->assign('restaurant_id', $restaurant_id);
            $this->assign('count',count($log_data));
            $this->display();return;
        }
        $page = new Page($count, $num);
        $limit = $page->firstRow . ',' . $page->listRows;
        $log_data = $M_log->where("goods_status = 1 AND creation_time >= {$today} AND order_num !=0 AND restaurant_id={$restaurant_id}")->order('creation_time ASC')->limit($limit)->select();
        $this->assign('restaurant_name',$restaurant_data['restaurant_name']);
        //cprint($log_data);die;
        $this->assign('restaurant_id', $restaurant_id);
        $this->assign('p',$p+2);
        $this->assign('datas',$log_data);
        $this->assign('count',count($log_data));
        $this->display();
    }


    //修改订单菜单状态
    // public function doType(){
    //     $ogId = $this->_post("ogid");
    //     $ogIds = explode(',',$ogId);
    //     array_pop($ogIds);
    //     $type = $this->_post("type")+1;
    //     $restaurantId = $this->_post('restaurant_id');
    //     $res = 0;
    //     if(!empty($ogIds) && ($type==1 || $type ==2)) {
    //         $M_order = M("restaurantstyy_order_goods");
    //         $condition['og_id'] = array('in',$ogIds);
    //         $condition['restaurant_id'] = $restaurantId;
    //         $res = $M_order->where($condition)->save(array('goods_status' => $type));

    //         if($res) {
    //             //增加大屏幕上菜记录
    //             $M_log = M("restaurantstyy_order_goods_log");
    //             if ($type == 1) {
    //                 //给手机点餐的用户推送消息
    //                 import("@.Msgtpl.Base.RestaurantstyyMsgtpl");
    //                 $wechatInfo = D('Wechat/Wechat')->getInfo(array('account_id' => 60), array('wechat_id'));
    //                 $RestaurantMsgtpl = new RestaurantstyyMsgtpl($wechatInfo['wechat_id']);
    //                 foreach ($ogIds as $id){
    //                     $og_data = $M_order->where("og_id={$id}")->find();
    //                     $data['order_id'] = $og_data['order_id'];
    //                     $data['restaurant_id'] = $og_data['restaurant_id'];
    //                     $data['goods_name'] = $og_data['goods_name'];
    //                     $data['og_id'] = $id;
    //                     $data['order_num'] = $og_data['order_num'];
    //                     $data['goods_logo'] = $og_data['goods_logo'];
    //                     $data['up_time'] = time();
    //                     $data['creation_time'] = time();
    //                     $data['goods_status'] = 1;
    //                     $M_log->data($data)->add();
    //                     //给手机点餐的用户推送消息
    //                     $orderInfo = M('RestaurantstyyOrder')->field('res_id,restaurant_id,order_sn,order_num,user_id,order_id,create_time')->where(array('order_id'=>$og_data['order_id']))->find();
    //                     if($orderInfo['user_id']){
    //                         $orderInfo['og_id'] = $id;
    //                         $orderInfo['goods_name'] = $og_data['goods_name'];
    //                         $orderInfo['goods_num'] = $og_data['goods_num'];
    //                         $RestaurantMsgtpl->sendMessage($orderInfo, 60,2);
    //                     }

    //                 }
    //             } elseif ($type == 2) {
    //                 $res = $M_log->where($condition)->save(array('goods_status' => 2, 'up_time' => time()));
    //             }
    //         }
    //     }
    //     if($res){
    //         $this->ajaxReturn(array('status'=>'S','message'=>'操作成功'));
    //     }else{
    //         $this->ajaxReturn(array('status'=>'F','message'=>'操作失败'));
    //     }
    //     exit;
    // }


    //修改订单菜单状态
    public function doType(){
        $ogId = $this->_post("ogid");
        $restaurantId = $this->_post('restaurant_id');
        $res = 0;
        if(!empty($ogId)) {
            $M_order = M("restaurantstyy_order_goods");
            $condition['order_num'] = $ogId;
            $condition['restaurant_id'] = '30';
            $res = $M_order->where($condition)->save(array('goods_status' => 1));

            $message_data=$M_order->where($condition)->order('create_time DESC')->limit(1)->select();
      
            if($res) {
            	$this->sendMessage($message_data[0]['order_id'],$message_data[0]['user_id'],$ogId);
            }
        }
        if($res){
            $this->ajaxReturn(array('status'=>'S','message'=>'操作成功'));
        }else{
            $this->ajaxReturn(array('status'=>'F','message'=>'操作失败'));
        }
        exit;
    }

    public function sendMessage($orderId = '',$userId='',$ogId){

        //微信用户open_id
        $openId = D('User')->where(array('user_id' => $userId))->getField('open_id');

        // echo $orderId.'----'.$userId;
        // die();
        //订单信息
        $orderInfo = D('Base/RestaurantstyyOrder')->where(array('order_id'=>$orderId))->find();
        //餐厅信息
        $info = D('Base/RestaurantstyyInfo')->getByPk($orderInfo['restaurant_id']);

        //微信模板id
        $templateId = 'ekcQpaU1PITvupiX08I65E8HoaGyVv-E2caQU-WuwfM';
        //标题
        $first = '您于'. date("Y年m月d日 H:i", time()).'的订单,菜肴已完成,请取餐!';
        //餐厅名字
        // if(session('tableno_id')){
        //     if(session('tableno_id')<50){
                $keyword1 = '麦思威';
        //     }else{
        //         $keyword1 = '二食堂';
        //     }
        // }
        //餐厅电话
        $keyword2 = $info['mobile'];
        //点餐桌号s
        $keyword3 = session('tableno_id');
        //订单编号
        $keyword4 = $orderInfo['order_sn'];
        //备注说明
        $remark = '';
        //时间戳
        $time = $orderInfo['create_time'];
        $url = C('weixin') . "/restaurantstyy/ZduMobile/orderDetail/res_id/1/order_id/" . $orderId;
        //生成签名
        $array = array(
            'c' => 'smart',
            'a' => 'publicSendMsg',
            'url' => $url,
            'first' => $first,
            'keyword1' => $keyword1,
            'keyword2' => $keyword2,
            'keyword3' => $ogId,
            'keyword4' => $keyword4,
            'remark'   => $remark,
            'time'     => $time,
            'touser'   => $openId,
            'template_id'   => $templateId,
        );
        $sign = $this->getSign($array);

        $array['sig'] = $sign;
        $array = http_build_query($array);
        // echo $array;
        $url = 'http://www.zulg.com/api.php?'.$array;
        $code = $this->curl($url);
        // var_dump($code);

    }


     public function curl($url = '', $postParams= null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT,30);
        curl_setopt($ch, CURLOPT_HEADER,0);
        // post提交数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams);
        if(!is_array($postParams)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($postParams)
            ));
        }
        $output = json_decode(curl_exec($ch),true);

        curl_close($ch);
        //打印获得的数据
        return $output;
    }

    /**
     * @param $params  数组参数
     * @return string  获取签名
     */
    public function getSign($params,$type=''){

        $str = '';

        foreach($params as $k=>$v){
            $str .= $k . '=' .$v;
        }

        $str .='smart123456';

        $sign=md5($str);
        return $sign;
    }

}